package com.mvc.gulimall.product.service.impl;


import com.mvc.gulimall.product.service.CategoryBrandRelationService;
import com.mvc.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mvc.common.utils.PageUtils;
import com.mvc.common.utils.Query;

import com.mvc.gulimall.product.dao.CategoryDao;
import com.mvc.gulimall.product.entity.CategoryEntity;
import com.mvc.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.AbstractDocument;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listwiTree() {
        //查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //组装成父子的树形结构
        //1.1 找到所有的一级分类
        List<CategoryEntity> level1Merus = entities.stream().filter((categoryEntity) ->
                categoryEntity.getParentCid() == 0
        ).map((meun)->{
            meun.setChildren(getchildrens(meun,entities));
            return meun;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Merus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //ToDo 1.检查当前要删除的菜单，是否被背别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long groupId) {
        List<Long> path= new ArrayList<>();
        List<Long> parentPath = findParentPath(groupId, path);
        Collections.reverse(parentPath);
        return  parentPath.toArray(new  Long[parentPath.size()]);
    }

    /**
     * 级联更新
     * @param category
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());


    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        //查出所有的分类
        //1.查出一级分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        //2. 封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(itme -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, itme.getCatId().toString(), itme.getName());
                    //1.找当前3级分类
                    List<CategoryEntity> level3Catalog  = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", itme.getCatId()));
                    List<Catelog2Vo.Category3Vo> category3Vos=null;
                    if (level3Catalog!=null){
                        category3Vos = level3Catalog.stream().map(l3 -> {
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(itme.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);

                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());

            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    private List<Long> findParentPath(Long catelogId,List<Long> path){
        //收集当前节点id
        path.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),path);
        }
        return path;
    }


    //递归查找子菜单
    private List<CategoryEntity> getchildrens(CategoryEntity root ,  List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream().filter(CategoryEntity -> {
            return CategoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity->{
            categoryEntity.setChildren(getchildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}